<?php

declare(strict_types=1);

namespace app\api\controller\Card;

use app\BaseController;
use app\common\model\Card\Card as CardModel;
use app\common\model\Config as ConfigModel;
use app\common\model\Card\Order as OrderModel;
use app\common\model\Region as RegionModel;
use app\common\model\User\Record as RecordModel;
use app\common\model\User\User as UserModel;
use app\common\validate\Card\Card as CardValidate;
use app\common\validate\Card\Order as OrderValidate;
use app\common\validate\User\Record as RecordValidate;
use think\exception\ValidateException;

class Card extends BaseController
{
    public function index()
    {
        $typeid = $this->request->param('typeid');

        $userid = $this->request->param('userid');
        $keyword = $this->request->param('keyword');

        $User = UserModel::find($userid);

        if (!$User) {
            $this->error('用户不存在');
        }

        // 已购的cardid
        $CardIds = OrderModel::where(['userid' => $userid])->column('cardid');

        $where = [];

        // 查询card表不查询登录用户
        $where[] = ['userid', '<>', $userid];

        if ($CardIds) {
            $where[] = ['id', 'NOT IN', $CardIds];
        }

        if ($typeid) {
            $where[] = ['typeid', '=', $typeid];
        }
        if ($keyword) {
            $where[] = ['nickname', 'LIKE', "%$keyword%"];
        }
        $CardList = CardModel::where($where)->order('createtime', 'desc')->select();

        /* 
            不能查询出自己的名片
            不能查询出已购的名片

            已购的数据
                查询card_order => userid => 已购的cardid
        */

        $this->success('查询成功', null, $CardList);
    }
    public function card()
    {
        $userid = $this->request->param('userid');

        $User = UserModel::find($userid);

        if (!$User) {
            $this->error('用户不存在');
        }

        $Card = CardModel::withJoin(['type'])->where(['userid' => $userid])->find();

        $this->success('查询成功', null, $Card);
    }
    public function add()
    {
        $params = $this->request->param();

        $User = UserModel::find($params['userid']);

        if (!$User) {
            $this->error('用户不存在');
        }

        $Card = CardModel::find($params['cardid']);

        $CardPoint = ConfigModel::where(['key' => 'CardPoint'])->value('value');

        if ($Card) {
            // 更新
            $CardList = CardModel::where([['id', '<>', $params['cardid']]])->select();

            foreach ($CardList as $item) {
                if ($item['email'] == $params['email']) {
                    $this->error('该邮箱已存在');
                    break;
                }

                if ($item['mobile'] == $params['mobile']) {
                    $this->error('该手机号已存在');
                    break;
                }
            }

            $data = [
                'userid' => $params['userid'],
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'sex' => $params['sex'],
                'content' => $params['content'],
                'typeid' => $params['typeid'],
                'price' => $CardPoint
            ];

            if (!empty($params['code'])) {
                $parentpath = RegionModel::where(['code' => $params['code']])->value('parentpath');

                if (!$parentpath) {
                    $this->error('所选地区不存在');
                }

                [$province, $city, $district] = explode(',', $parentpath);

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = upload('avatar');

                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }

                $data['avatar'] = $avatar['data'];
            }

            $result = CardModel::update($data, ['id' => $params['cardid']]);

            if ($result !== FALSE) {
                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file((string)$Card['avatar']) && @unlink($Card['avatar']);
                }
                $this->success('生成名片成功');
            } else {
                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file((string)$data['avatar']) && @unlink($data['avatar']);
                }
                $this->error('生成名片失败');
            }
        } else {
            // 新增
            $data = [
                'userid' => $params['userid'],
                'nickname' => $params['nickname'],
                'mobile' => $params['mobile'],
                'email' => $params['email'],
                'sex' => $params['sex'],
                'content' => $params['content'],
                'typeid' => $params['typeid'],
                'price' => $CardPoint
            ];

            if (!empty($params['code'])) {
                $parentpath = RegionModel::where(['code' => $params['code']])->value('parentpath');

                if (!$parentpath) {
                    $this->error('所选地区不存在');
                }

                [$province, $city, $district] = explode(',', $parentpath);

                $data['province'] = $province;
                $data['city'] = $city;
                $data['district'] = $district;
            }

            if (isset($_FILES['avatar']) && $_FILES['avatar']['size'] > 0) {
                $avatar = upload('avatar');

                if ($avatar['code'] === 0) {
                    $this->error($avatar['msg']);
                }

                $data['avatar'] = $avatar['data'];
            }

            try {
                validate(CardValidate::class)->check($data);
            } catch (ValidateException $e) {
                $this->error($e->getError());
            }

            $result = CardModel::create($data);

            if ($result !== FALSE) {
                $this->success('生成名片成功');
            } else {
                if (!empty($data['avatar']) && $_FILES['avatar']['size'] > 0) {
                    @is_file((string)$data['avatar']) && @unlink($data['avatar']);
                }
                $this->error('生成名片失败');
            }
        }
    }
    public function pay()
    {
        $userid = $this->request->param('userid');
        $cardid = $this->request->param('cardid');
        $User = UserModel::find($userid);
        if (!$User) {
            $this->error('用户不存在');
        }
        $Card = CardModel::find($cardid);
        if (!$Card) {
            $this->error('名片不存在');
        }
        try {
            // 用户积分
            // 消费记录
            // 名片订单
            UserModel::startTrans();
            OrderModel::startTrans();
            RecordModel::startTrans();
            $data = [
                'userid' => $userid,
                'cardid' => $cardid,
                'price' => $Card['price']
            ];

            validate(OrderValidate::class)->check($data);
            // 新增订单
            $OrderStatus = OrderModel::create($data);
            // 判断是否新增成功
            if ($OrderStatus === FALSE) {
                throw new \Exception('新增订单失败');
            }

            // 积分判断
            $point = bcsub((string)$User['point'], (string)$Card['price']);
            if ($point < 0) {
                throw new \Exception('积分不足，请先充值');
            }
            $User->point = bcsub((string)$User['point'], (string)$Card['price']);
            $UserStatus = $User->save();
            // 判断是否新增成功
            if ($UserStatus === FALSE) {
                throw new \Exception('新增订单失败');
            }
            // 新增消费记录
            $RecordData = [
                'point' => $Card['price'],
                'content' => "您购买的名片{$Card['nickname']}消费了{$Card['price']}积分",
                'state' => 7,
                'userid' => $userid
            ];
            // 验证数据
            validate(RecordValidate::class)->check($RecordData);
            // 新增
            $RecordStatus = RecordModel::create($RecordData);
            // 判断是否成功
            if ($RecordStatus === FALSE) {
                throw new \Exception('新增消费记录失败');
            }
        } catch (ValidateException $e) {
            UserModel::rollback();
            OrderModel::rollback();
            RecordModel::rollback();
            $this->error($e->getError());
        } catch (\Exception $error) {
            UserModel::rollback();
            OrderModel::rollback();
            RecordModel::rollback();
            $this->error($error->getMessage());
        }
        UserModel::commit();
        OrderModel::commit();
        RecordModel::commit();
        $this->success('购买成功');
    }
}
